<template>
  <div class="emergency-linkage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">应急联动管理</h2>
      <p class="page-description">管理水库应急预案、联动机制和演练记录</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalPlans }}</div>
              <div class="stat-label">应急预案</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalMechanisms }}</div>
              <div class="stat-label">联动机制</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Operation /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalDrills }}</div>
              <div class="stat-label">演练记录</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Phone /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalContacts }}</div>
              <div class="stat-label">应急联系人</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-tabs v-model="activeTab" type="card" @tab-change="handleTabChange">
        <!-- 应急预案 -->
        <el-tab-pane label="应急预案" name="plans">
          <div class="tab-content">
            <!-- 查询条件 -->
            <el-card shadow="hover" style="margin-bottom: 8px">
              <el-form :model="planQuery" inline>
                <el-form-item label="预案名称">
                  <el-input
                    v-model="planQuery.name"
                    placeholder="请输入预案名称"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="预案类型">
                  <el-select v-model="planQuery.type" placeholder="请选择类型" clearable style="width: 150px">
                    <el-option label="防洪预案" value="flood" />
                    <el-option label="抗旱预案" value="drought" />
                    <el-option label="设备故障" value="equipment" />
                    <el-option label="安全事故" value="safety" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="planQuery.status" placeholder="请选择状态" clearable style="width: 120px">
                    <el-option label="有效" value="active" />
                    <el-option label="修订中" value="revising" />
                    <el-option label="已废止" value="obsolete" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchPlans">查询</el-button>
                  <el-button :icon="Refresh" @click="resetPlanQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 操作按钮 -->
            <el-card class="operation-card" shadow="hover" style="margin-bottom: 8px">
              <el-row :gutter="10">
                <el-col :span="24">
                  <el-button type="primary" :icon="Plus" @click="handleAddPlan">新增预案</el-button>
                  <el-button :icon="Download" @click="exportPlans">导出预案</el-button>
                  <el-button type="warning" :icon="Bell" @click="activateEmergency">启动应急</el-button>
                </el-col>
              </el-row>
            </el-card>

            <!-- 数据表格 -->
            <el-table :data="planList" border style="width: 100%">
              <el-table-column prop="name" label="预案名称" width="200" />
              <el-table-column prop="type" label="预案类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getPlanTypeTag(row.type)">
                    {{ getPlanTypeText(row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="level" label="响应级别" width="100">
                <template #default="{ row }">
                  <el-tag :type="getLevelTag(row.level)">
                    {{ getLevelText(row.level) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="version" label="版本号" width="100" />
              <el-table-column prop="createDate" label="制定日期" width="120" />
              <el-table-column prop="updateDate" label="更新日期" width="120" />
              <el-table-column prop="responsible" label="负责人" width="120" />
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="getPlanStatusTag(row.status)">
                    {{ getPlanStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="viewPlanDetail(row)">查看</el-button>
                  <el-button type="primary" link @click="editPlan(row)">编辑</el-button>
                  <el-button type="success" link @click="activatePlan(row)">启动</el-button>
                  <el-button type="danger" link @click="deletePlan(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-section">
              <el-pagination
                v-model:current-page="planPagination.currentPage"
                v-model:page-size="planPagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="planPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePlanSizeChange"
                @current-change="handlePlanCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 联动机制 -->
        <el-tab-pane label="联动机制" name="mechanisms">
          <div class="tab-content">
            <!-- 查询条件 -->
            <div class="query-section">
              <el-form :model="mechanismQuery" inline>
                <el-form-item label="机制名称">
                  <el-input
                    v-model="mechanismQuery.name"
                    placeholder="请输入机制名称"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="联动类型">
                  <el-select v-model="mechanismQuery.type" placeholder="请选择类型" clearable style="width: 150px">
                    <el-option label="部门联动" value="department" />
                    <el-option label="区域联动" value="regional" />
                    <el-option label="专业联动" value="professional" />
                    <el-option label="社会联动" value="social" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchMechanisms">查询</el-button>
                  <el-button :icon="Refresh" @click="resetMechanismQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <div class="action-section">
              <el-button type="primary" :icon="Plus" @click="handleAddMechanism">新增机制</el-button>
              <el-button :icon="Setting" @click="configureMechanism">配置联动</el-button>
            </div>

            <!-- 联动机制卡片 -->
            <div class="mechanism-grid">
              <div
                v-for="mechanism in mechanismList"
                :key="mechanism.id"
                class="mechanism-card"
                @click="viewMechanismDetail(mechanism)"
              >
                <div class="mechanism-header">
                  <div class="mechanism-title">{{ mechanism.name }}</div>
                  <el-tag :type="getMechanismTypeTag(mechanism.type)">
                    {{ getMechanismTypeText(mechanism.type) }}
                  </el-tag>
                </div>
                <div class="mechanism-content">
                  <p class="mechanism-description">{{ mechanism.description }}</p>
                  <div class="mechanism-participants">
                    <div class="participant-label">参与单位：</div>
                    <div class="participant-list">
                      <el-tag
                        v-for="participant in mechanism.participants"
                        :key="participant"
                        size="small"
                        type="info"
                        effect="plain"
                      >
                        {{ participant }}
                      </el-tag>
                    </div>
                  </div>
                </div>
                <div class="mechanism-footer">
                  <div class="mechanism-meta">
                    <span class="meta-item">负责人：{{ mechanism.responsible }}</span>
                    <span class="meta-item">更新时间：{{ mechanism.updateDate }}</span>
                  </div>
                  <div class="mechanism-actions">
                    <el-button type="primary" link @click.stop="editMechanism(mechanism)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="success" link @click.stop="testMechanism(mechanism)">
                      <el-icon><VideoPlay /></el-icon>
                    </el-button>
                    <el-button type="danger" link @click.stop="deleteMechanism(mechanism)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <el-pagination
                v-model:current-page="mechanismPagination.currentPage"
                v-model:page-size="mechanismPagination.pageSize"
                :page-sizes="[6, 12, 24, 48]"
                :total="mechanismPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleMechanismSizeChange"
                @current-change="handleMechanismCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 演练记录 -->
        <el-tab-pane label="演练记录" name="drills">
          <div class="tab-content">
            <!-- 查询条件 -->
            <div class="query-section">
              <el-form :model="drillQuery" inline>
                <el-form-item label="演练名称">
                  <el-input
                    v-model="drillQuery.name"
                    placeholder="请输入演练名称"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="演练类型">
                  <el-select v-model="drillQuery.type" placeholder="请选择类型" clearable style="width: 150px">
                    <el-option label="桌面演练" value="desktop" />
                    <el-option label="功能演练" value="functional" />
                    <el-option label="全面演练" value="comprehensive" />
                    <el-option label="实战演练" value="actual" />
                  </el-select>
                </el-form-item>
                <el-form-item label="演练时间">
                  <el-date-picker
                    v-model="drillQuery.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 240px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchDrills">查询</el-button>
                  <el-button :icon="Refresh" @click="resetDrillQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <div class="action-section">
              <el-button type="primary" :icon="Plus" @click="handleAddDrill">新增演练</el-button>
              <el-button :icon="Calendar" @click="scheduleDrill">演练计划</el-button>
              <el-button :icon="PieChart" @click="drillStatistics">演练统计</el-button>
            </div>

            <!-- 演练时间线 -->
            <div class="drill-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="drill in drillList"
                  :key="drill.id"
                  :timestamp="drill.date"
                  placement="top"
                  :type="getDrillTimelineType(drill.result)"
                >
                  <el-card class="drill-card">
                    <div class="drill-header">
                      <h4 class="drill-title">{{ drill.name }}</h4>
                      <div class="drill-badges">
                        <el-tag :type="getDrillTypeTag(drill.type)">
                          {{ getDrillTypeText(drill.type) }}
                        </el-tag>
                        <el-tag :type="getDrillResultTag(drill.result)">
                          {{ getDrillResultText(drill.result) }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="drill-content">
                      <p class="drill-scenario">演练场景：{{ drill.scenario }}</p>
                      <div class="drill-details">
                        <div class="detail-item">
                          <span class="detail-label">参与人数：</span>
                          <span class="detail-value">{{ drill.participants }}人</span>
                        </div>
                        <div class="detail-item">
                          <span class="detail-label">持续时间：</span>
                          <span class="detail-value">{{ drill.duration }}分钟</span>
                        </div>
                        <div class="detail-item">
                          <span class="detail-label">组织单位：</span>
                          <span class="detail-value">{{ drill.organizer }}</span>
                        </div>
                      </div>
                      <div class="drill-summary">
                        <p>{{ drill.summary }}</p>
                      </div>
                    </div>
                    <div class="drill-actions">
                      <el-button type="primary" link @click="viewDrillDetail(drill)">查看详情</el-button>
                      <el-button type="primary" link @click="viewDrillReport(drill)">查看报告</el-button>
                      <el-button type="success" link @click="downloadDrillFiles(drill)">下载资料</el-button>
                      <el-button type="danger" link @click="deleteDrill(drill)">删除</el-button>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <el-pagination
                v-model:current-page="drillPagination.currentPage"
                v-model:page-size="drillPagination.pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="drillPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleDrillSizeChange"
                @current-change="handleDrillCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- 应急联系人 -->
        <el-tab-pane label="应急联系人" name="contacts">
          <div class="tab-content">
            <!-- 查询条件 -->
            <div class="query-section">
              <el-form :model="contactQuery" inline>
                <el-form-item label="姓名">
                  <el-input
                    v-model="contactQuery.name"
                    placeholder="请输入姓名"
                    clearable
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item label="职责">
                  <el-select v-model="contactQuery.role" placeholder="请选择职责" clearable style="width: 150px">
                    <el-option label="总指挥" value="commander" />
                    <el-option label="副总指挥" value="deputy" />
                    <el-option label="技术专家" value="expert" />
                    <el-option label="现场负责人" value="site_manager" />
                    <el-option label="联络员" value="liaison" />
                  </el-select>
                </el-form-item>
                <el-form-item label="单位">
                  <el-input
                    v-model="contactQuery.organization"
                    placeholder="请输入单位"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :icon="Search" @click="searchContacts">查询</el-button>
                  <el-button :icon="Refresh" @click="resetContactQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <div class="action-section">
              <el-button type="primary" :icon="Plus" @click="handleAddContact">新增联系人</el-button>
              <el-button :icon="Download" @click="exportContacts">导出通讯录</el-button>
              <el-button type="warning" :icon="Message" @click="sendNotification">发送通知</el-button>
            </div>

            <!-- 联系人卡片 -->
            <div class="contact-grid">
              <div
                v-for="contact in contactList"
                :key="contact.id"
                class="contact-card"
              >
                <div class="contact-avatar">
                  <el-avatar :size="60" :src="contact.avatar">
                    {{ contact.name.charAt(0) }}
                  </el-avatar>
                </div>
                <div class="contact-info">
                  <h4 class="contact-name">{{ contact.name }}</h4>
                  <div class="contact-role">
                    <el-tag :type="getRoleTag(contact.role)">
                      {{ getRoleText(contact.role) }}
                    </el-tag>
                  </div>
                  <div class="contact-details">
                    <div class="detail-row">
                      <el-icon><OfficeBuilding /></el-icon>
                      <span>{{ contact.organization }}</span>
                    </div>
                    <div class="detail-row">
                      <el-icon><Phone /></el-icon>
                      <span>{{ contact.phone }}</span>
                    </div>
                    <div class="detail-row">
                      <el-icon><Message /></el-icon>
                      <span>{{ contact.email }}</span>
                    </div>
                  </div>
                </div>
                <div class="contact-actions">
                  <el-button type="success" circle @click="callContact(contact)">
                    <el-icon><Phone /></el-icon>
                  </el-button>
                  <el-button type="primary" circle @click="messageContact(contact)">
                    <el-icon><ChatDotRound /></el-icon>
                  </el-button>
                  <el-button type="info" circle @click="editContact(contact)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button type="danger" circle @click="deleteContact(contact)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-section">
              <el-pagination
                v-model:current-page="contactPagination.currentPage"
                v-model:page-size="contactPagination.pageSize"
                :page-sizes="[8, 16, 32, 64]"
                :total="contactPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleContactSizeChange"
                @current-change="handleContactCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Plus, Download, Refresh, Bell, Setting, Calendar, PieChart,
  Warning, Connection, Operation, Phone, Edit, Delete, VideoPlay,
  Message, ChatDotRound, OfficeBuilding
} from '@element-plus/icons-vue'

// 页面数据
const activeTab = ref('plans')

// 工具与通用方法
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[Math.floor(Math.random() * arr.length)]
const pad2 = (n: number) => (n < 10 ? `0${n}` : `${n}`)
const formatDate = (d: Date) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`

// 全量数据存储（保持删除、筛选与分页一致性）
const allPlans = ref<any[]>([])
const allMechanisms = ref<any[]>([])
const allDrills = ref<any[]>([])
const allContacts = ref<any[]>([])

const updateStats = () => {
  statsData.totalPlans = allPlans.value.length
  statsData.totalMechanisms = allMechanisms.value.length
  statsData.totalDrills = allDrills.value.length
  statsData.totalContacts = allContacts.value.length
}

// 生成与应用 —— 应急预案
const generateMockPlans = () => {
  if (allPlans.value.length) return
  const types = ['flood', 'drought', 'equipment', 'safety', 'other']
  const levels = ['I', 'II', 'III', 'IV']
  const responsibles = ['张三', '李四', '王五', '赵六']
  const statuses = ['active', 'revising', 'obsolete']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    const c = new Date(2023, randInt(0, 11), randInt(1, 28))
    const u = new Date(2024, randInt(0, 9), randInt(1, 28))
    base.push({
      id: i + 1,
      name: `应急预案-${i + 1}`,
      type: randomChoice(types),
      level: randomChoice(levels),
      version: `V${randInt(1, 3)}.${randInt(0, 9)}`,
      createDate: formatDate(c),
      updateDate: formatDate(u),
      responsible: randomChoice(responsibles),
      status: randomChoice(statuses)
    })
  }
  allPlans.value = base
}

const applyPlans = () => {
  let data = [...allPlans.value]
  if (planQuery.name?.trim()) {
    const kw = planQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (planQuery.type) data = data.filter(i => i.type === planQuery.type)
  if (planQuery.status) data = data.filter(i => i.status === planQuery.status)
  planPagination.total = data.length
  const startIdx = (planPagination.currentPage - 1) * planPagination.pageSize
  planList.value = data.slice(startIdx, startIdx + planPagination.pageSize)
}

// 生成与应用 —— 联动机制
const generateMockMechanisms = () => {
  if (allMechanisms.value.length) return
  const types = ['department', 'regional', 'professional', 'social']
  const participants = ['水利局', '气象局', '应急管理局', '城管局', '技术部', '维护班', '外包公司', '设备厂商']
  const responsibles = ['张三', '李四', '王五', '赵六']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    base.push({
      id: i + 1000,
      name: `联动机制-${i + 1}`,
      type: randomChoice(types),
      description: '示例联动机制描述',
      participants: Array.from({ length: randInt(2, 5) }, () => randomChoice(participants)),
      responsible: randomChoice(responsibles),
      updateDate: formatDate(new Date(2024, randInt(0, 9), randInt(1, 28)))
    })
  }
  allMechanisms.value = base
}

const applyMechanisms = () => {
  let data = [...allMechanisms.value]
  if (mechanismQuery.name?.trim()) {
    const kw = mechanismQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (mechanismQuery.type) data = data.filter(i => i.type === mechanismQuery.type)
  mechanismPagination.total = data.length
  const startIdx = (mechanismPagination.currentPage - 1) * mechanismPagination.pageSize
  mechanismList.value = data.slice(startIdx, startIdx + mechanismPagination.pageSize)
}

// 生成与应用 —— 演练记录
const generateMockDrills = () => {
  if (allDrills.value.length) return
  const types = ['desktop', 'functional', 'comprehensive', 'actual']
  const results = ['excellent', 'good', 'fair', 'poor']
  const organizers = ['水库管理处', '技术部', '应急管理局']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    const d = new Date(2023, randInt(0, 11), randInt(1, 28))
    base.push({
      id: i + 2000,
      name: `演练记录-${i + 1}`,
      type: randomChoice(types),
      date: formatDate(d),
      scenario: '示例演练场景',
      participants: randInt(10, 60),
      duration: randInt(30, 180),
      organizer: randomChoice(organizers),
      result: randomChoice(results),
      summary: '演练过程记录摘要...'
    })
  }
  allDrills.value = base
}

const applyDrills = () => {
  let data = [...allDrills.value]
  if (drillQuery.name?.trim()) {
    const kw = drillQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (drillQuery.type) data = data.filter(i => i.type === drillQuery.type)
  if (Array.isArray(drillQuery.dateRange) && drillQuery.dateRange.length === 2) {
    const [start, end] = drillQuery.dateRange
    const startTs = new Date(start + ' 00:00:00').getTime()
    const endTs = new Date(end + ' 23:59:59').getTime()
    data = data.filter(i => {
      const ts = new Date(i.date).getTime()
      return ts >= startTs && ts <= endTs
    })
  }
  drillPagination.total = data.length
  const startIdx = (drillPagination.currentPage - 1) * drillPagination.pageSize
  drillList.value = data.slice(startIdx, startIdx + drillPagination.pageSize)
}

// 生成与应用 —— 应急联系人
const generateMockContacts = () => {
  if (allContacts.value.length) return
  const roles = ['commander', 'deputy', 'expert', 'site_manager', 'liaison']
  const orgs = ['水库管理处', '水利技术中心', '应急管理局', '城管局', '外部合作单位']
  const count = randInt(10, 50)
  const base: any[] = []
  for (let i = 0; i < count; i++) {
    base.push({
      id: i + 3000,
      name: `联系人-${i + 1}`,
      role: randomChoice(roles),
      organization: randomChoice(orgs),
      phone: `138${pad2(randInt(10, 99))}${pad2(randInt(10, 99))}${pad2(randInt(10, 99))}`,
      email: `user${i + 1}@example.com`,
      avatar: ''
    })
  }
  allContacts.value = base
}

const applyContacts = () => {
  let data = [...allContacts.value]
  if (contactQuery.name?.trim()) {
    const kw = contactQuery.name.trim().toLowerCase()
    data = data.filter(i => `${i.name}`.toLowerCase().includes(kw))
  }
  if (contactQuery.role) data = data.filter(i => i.role === contactQuery.role)
  if (contactQuery.organization?.trim()) {
    const kw = contactQuery.organization.trim().toLowerCase()
    data = data.filter(i => `${i.organization}`.toLowerCase().includes(kw))
  }
  contactPagination.total = data.length
  const startIdx = (contactPagination.currentPage - 1) * contactPagination.pageSize
  contactList.value = data.slice(startIdx, startIdx + contactPagination.pageSize)
}

// 统计数据
const statsData = reactive({
  totalPlans: 12,
  totalMechanisms: 8,
  totalDrills: 25,
  totalContacts: 36
})

// 应急预案相关数据
const planQuery = reactive({
  name: '',
  type: '',
  status: ''
})

const planList = ref<any[]>([])
const planPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 联动机制相关数据
const mechanismQuery = reactive({
  name: '',
  type: ''
})

const mechanismList = ref<any[]>([])
const mechanismPagination = reactive({
  currentPage: 1,
  pageSize: 6,
  total: 0
})

// 演练记录相关数据
const drillQuery = reactive({
  name: '',
  type: '',
  dateRange: null as any
})

const drillList = ref<any[]>([])
const drillPagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 应急联系人相关数据
const contactQuery = reactive({
  name: '',
  role: '',
  organization: ''
})

const contactList = ref<any[]>([])
const contactPagination = reactive({
  currentPage: 1,
  pageSize: 8,
  total: 0
})

// 应急预案相关方法
const getPlanTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    flood: '防洪预案',
    drought: '抗旱预案',
    equipment: '设备故障',
    safety: '安全事故',
    other: '其他'
  }
  return typeMap[type] || type
}

const getPlanTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    flood: 'primary',
    drought: 'warning',
    equipment: 'danger',
    safety: 'success',
    other: 'info'
  }
  return tagMap[type] || 'info'
}

const getLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    I: 'Ⅰ级',
    II: 'Ⅱ级',
    III: 'Ⅲ级',
    IV: 'Ⅳ级'
  }
  return levelMap[level] || level
}

const getLevelTag = (level: string) => {
  const tagMap: Record<string, string> = {
    I: 'danger',
    II: 'warning',
    III: 'primary',
    IV: 'success'
  }
  return tagMap[level] || 'info'
}

const getPlanStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '有效',
    revising: '修订中',
    obsolete: '已废止'
  }
  return statusMap[status] || status
}

const getPlanStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    active: 'success',
    revising: 'warning',
    obsolete: 'info'
  }
  return tagMap[status] || 'info'
}

// 联动机制相关方法
const getMechanismTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    department: '部门联动',
    regional: '区域联动',
    professional: '专业联动',
    social: '社会联动'
  }
  return typeMap[type] || type
}

const getMechanismTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    department: 'primary',
    regional: 'success',
    professional: 'warning',
    social: 'info'
  }
  return tagMap[type] || 'info'
}

// 演练记录相关方法
const getDrillTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    desktop: '桌面演练',
    functional: '功能演练',
    comprehensive: '全面演练',
    actual: '实战演练'
  }
  return typeMap[type] || type
}

const getDrillTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    desktop: 'info',
    functional: 'primary',
    comprehensive: 'warning',
    actual: 'danger'
  }
  return tagMap[type] || 'info'
}

const getDrillResultText = (result: string) => {
  const resultMap: Record<string, string> = {
    excellent: '优秀',
    good: '良好',
    fair: '一般',
    poor: '较差'
  }
  return resultMap[result] || result
}

const getDrillResultTag = (result: string) => {
  const tagMap: Record<string, string> = {
    excellent: 'success',
    good: 'primary',
    fair: 'warning',
    poor: 'danger'
  }
  return tagMap[result] || 'info'
}

const getDrillTimelineType = (result: string) => {
  const typeMap: Record<string, string> = {
    excellent: 'success',
    good: 'primary',
    fair: 'warning',
    poor: 'danger'
  }
  return typeMap[result] || 'info'
}

// 应急联系人相关方法
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    commander: '总指挥',
    deputy: '副总指挥',
    expert: '技术专家',
    site_manager: '现场负责人',
    liaison: '联络员'
  }
  return roleMap[role] || role
}

const getRoleTag = (role: string) => {
  const tagMap: Record<string, string> = {
    commander: 'danger',
    deputy: 'warning',
    expert: 'primary',
    site_manager: 'success',
    liaison: 'info'
  }
  return tagMap[role] || 'info'
}

// 页面操作方法
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  loadTabData(tabName)
}

const loadTabData = (tabName: string) => {
  switch (tabName) {
    case 'plans':
      loadPlanData()
      break
    case 'mechanisms':
      loadMechanismData()
      break
    case 'drills':
      loadDrillData()
      break
    case 'contacts':
      loadContactData()
      break
  }
}

// 应急预案操作方法
const loadPlanData = () => {
  if (!allPlans.value.length) generateMockPlans()
  applyPlans()
  updateStats()
}

const searchPlans = () => {
  loadPlanData()
}

const resetPlanQuery = () => {
  Object.assign(planQuery, {
    name: '',
    type: '',
    status: ''
  })
  loadPlanData()
}

const handleAddPlan = () => {
  ElMessage.info('新增预案功能开发中...')
}

const exportPlans = () => {
  ElMessage.success('导出预案成功')
}

const activateEmergency = () => {
  ElMessage.warning('启动应急响应功能开发中...')
}

const viewPlanDetail = (row: any) => {
  ElMessage.info(`查看预案详情：${row.name}`)
}

const editPlan = (row: any) => {
  ElMessage.info(`编辑预案：${row.name}`)
}

const activatePlan = (row: any) => {
  ElMessage.warning(`启动预案：${row.name}`)
}

const deletePlan = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除预案"${row.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allPlans.value.findIndex(i => i.id === row.id)
    if (idx !== -1) allPlans.value.splice(idx, 1)
    applyPlans()
    updateStats()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handlePlanSizeChange = (size: number) => {
  planPagination.pageSize = size
  loadPlanData()
}

const handlePlanCurrentChange = (page: number) => {
  planPagination.currentPage = page
  loadPlanData()
}

// 联动机制操作方法
const loadMechanismData = () => {
  if (!allMechanisms.value.length) generateMockMechanisms()
  applyMechanisms()
  updateStats()
}

const searchMechanisms = () => {
  loadMechanismData()
}

const resetMechanismQuery = () => {
  Object.assign(mechanismQuery, {
    name: '',
    type: ''
  })
  loadMechanismData()
}

const handleAddMechanism = () => {
  ElMessage.info('新增联动机制功能开发中...')
}

const configureMechanism = () => {
  ElMessage.info('配置联动功能开发中...')
}

const viewMechanismDetail = (mechanism: any) => {
  ElMessage.info(`查看联动机制详情：${mechanism.name}`)
}

const editMechanism = (mechanism: any) => {
  ElMessage.info(`编辑联动机制：${mechanism.name}`)
}

const testMechanism = (mechanism: any) => {
  ElMessage.info(`测试联动机制：${mechanism.name}`)
}

const deleteMechanism = async (mechanism: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除联动机制"${mechanism.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allMechanisms.value.findIndex(i => i.id === mechanism.id)
    if (idx !== -1) allMechanisms.value.splice(idx, 1)
    applyMechanisms()
    updateStats()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleMechanismSizeChange = (size: number) => {
  mechanismPagination.pageSize = size
  loadMechanismData()
}

const handleMechanismCurrentChange = (page: number) => {
  mechanismPagination.currentPage = page
  loadMechanismData()
}

// 演练记录操作方法
const loadDrillData = () => {
  if (!allDrills.value.length) generateMockDrills()
  applyDrills()
  updateStats()
}

const searchDrills = () => {
  loadDrillData()
}

const resetDrillQuery = () => {
  Object.assign(drillQuery, {
    name: '',
    type: '',
    dateRange: null
  })
  loadDrillData()
}

const handleAddDrill = () => {
  ElMessage.info('新增演练记录功能开发中...')
}

const scheduleDrill = () => {
  ElMessage.info('演练计划功能开发中...')
}

const drillStatistics = () => {
  ElMessage.info('演练统计功能开发中...')
}

const viewDrillDetail = (drill: any) => {
  ElMessage.info(`查看演练详情：${drill.name}`)
}

const viewDrillReport = (drill: any) => {
  ElMessage.info(`查看演练报告：${drill.name}`)
}

const downloadDrillFiles = (drill: any) => {
  ElMessage.success(`下载演练资料：${drill.name}`)
}

const deleteDrill = async (drill: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除演练记录"${drill.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allDrills.value.findIndex(i => i.id === drill.id)
    if (idx !== -1) allDrills.value.splice(idx, 1)
    applyDrills()
    updateStats()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleDrillSizeChange = (size: number) => {
  drillPagination.pageSize = size
  loadDrillData()
}

const handleDrillCurrentChange = (page: number) => {
  drillPagination.currentPage = page
  loadDrillData()
}

// 应急联系人操作方法
const loadContactData = () => {
  if (!allContacts.value.length) generateMockContacts()
  applyContacts()
  updateStats()
}

const searchContacts = () => {
  loadContactData()
}

const resetContactQuery = () => {
  Object.assign(contactQuery, {
    name: '',
    role: '',
    organization: ''
  })
  loadContactData()
}

const handleAddContact = () => {
  ElMessage.info('新增联系人功能开发中...')
}

const exportContacts = () => {
  ElMessage.success('导出通讯录成功')
}

const sendNotification = () => {
  ElMessage.info('发送通知功能开发中...')
}

const callContact = (contact: any) => {
  ElMessage.success(`正在拨打 ${contact.name} 的电话：${contact.phone}`)
}

const messageContact = (contact: any) => {
  ElMessage.info(`发送消息给：${contact.name}`)
}

const editContact = (contact: any) => {
  ElMessage.info(`编辑联系人：${contact.name}`)
}

const deleteContact = async (contact: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除联系人"${contact.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const idx = allContacts.value.findIndex(i => i.id === contact.id)
    if (idx !== -1) allContacts.value.splice(idx, 1)
    applyContacts()
    updateStats()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleContactSizeChange = (size: number) => {
  contactPagination.pageSize = size
  loadContactData()
}

const handleContactCurrentChange = (page: number) => {
  contactPagination.currentPage = page
  loadContactData()
}

// 页面初始化
onMounted(() => {
  loadTabData(activeTab.value)
})
</script>

<style scoped>
.emergency-linkage {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  background: linear-gradient(135deg, #f56c6c, #ff8a8a);
  color: white;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tab-content {
  padding: 20px;
}

.query-section {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.action-section {
  margin-bottom: 16px;
}

.pagination-section {
  margin-top: 16px;
  text-align: right;
}

/* 联动机制卡片样式 */
.mechanism-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.mechanism-card {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.mechanism-card:hover {
  border-color: #f56c6c;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.mechanism-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.mechanism-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.mechanism-content {
  margin-bottom: 16px;
}

.mechanism-description {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
}

.mechanism-participants {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.participant-label {
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}

.participant-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.mechanism-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mechanism-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-item {
  color: #909399;
  font-size: 12px;
}

.mechanism-actions {
  display: flex;
  gap: 4px;
}

/* 演练时间线样式 */
.drill-timeline {
  margin-bottom: 20px;
}

.drill-card {
  margin-bottom: 0;
}

.drill-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.drill-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.drill-badges {
  display: flex;
  gap: 8px;
}

.drill-content {
  margin-bottom: 16px;
}

.drill-scenario {
  color: #606266;
  margin-bottom: 12px;
}

.drill-details {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.detail-label {
  color: #909399;
  font-size: 14px;
}

.detail-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.drill-summary {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.drill-summary p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.drill-actions {
  display: flex;
  gap: 8px;
}

/* 联系人卡片样式 */
.contact-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.contact-card {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s;
}

.contact-card:hover {
  border-color: #f56c6c;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.contact-avatar {
  margin-bottom: 16px;
}

.contact-info {
  margin-bottom: 16px;
}

.contact-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.contact-role {
  margin-bottom: 12px;
}

.contact-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.contact-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
}

:deep(.el-tabs__header) {
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

:deep(.el-tabs__item) {
  height: 50px;
  line-height: 50px;
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-timeline-item__timestamp) {
  font-weight: 500;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}
</style>